package com.bourse.core.services.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.bourse.core.enums.LogFileType;
import com.bourse.core.ibatis.MailingDao;

public class MailServiceImpl implements MailService {

	private static final Logger LOGGER = Logger
			.getLogger(MailServiceImpl.class);

	private String smtpHostName;

	private String smtpAuthUser;

	private String smtpAuthPassword;

	private String emailFromAddress;

	private MailingDao mailingDao;

	private String logDir;

	/**
	 * 
	 */
	public void sendDbFeederLogStatus() throws MessagingException {

		// Prepare recipient
		List<MailingData> mailingDatas = mailingDao.getMailingData();
		List<String> recipientList = new ArrayList<String>();
		for (int i = 0; i < mailingDatas.size(); i++) {
			MailingData mailingData = mailingDatas.get(i);
			if (mailingData.isLogSend()) {
				recipientList.add(mailingData.getRecipient());
			}
		}

		// Prepare pj
		List<String> pjs = new ArrayList<String>();
		pjs.add(LogFileType.INFO.getName());
		pjs.add(LogFileType.DEBUG.getName());
		pjs.add(LogFileType.WARNING.getName());
		pjs.add(LogFileType.ERROR.getName());
		pjs.add(LogFileType.FATAL.getName());
		
		// Prepare message informations
		String title = "[DBFEEDER MAIL SERVICE] - Application log status";
		String message = "En pj les logs de l'application DbFeeder. ";
		postMail(title, message, recipientList, pjs, logDir);
		
	}

	/**
	 * 
	 */
	public void postMail(String title, String bodyPart, List<String> to,
			List<String> pieceJointes, String attachmentDir)
			throws MessagingException {

		LOGGER.info("[MAIL SERVICE] - Preparing to send mail");

		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", smtpHostName);
		props.put("mail.smtp.auth", "true");

		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);
		session.setDebug(false);

		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(emailFromAddress));

		// Set receivers.
		InternetAddress[] addressTo = new InternetAddress[to.size()];
		for (int i = 0; i < to.size(); i++) {
			addressTo[i] = new InternetAddress(to.get(i));
		}
		msg.setRecipients(Message.RecipientType.BCC, addressTo);

		// Mail subject
		msg.setSubject(title);

		// Main text message
		BodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText(bodyPart);

		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);
		
		// Pièce jointes
		if (pieceJointes != null && attachmentDir != null) {
			for (int i = 0; i < pieceJointes.size(); i++) {
				messageBodyPart = new MimeBodyPart();
				DataSource source = new FileDataSource(attachmentDir
						+ pieceJointes.get(i));
				messageBodyPart.setDataHandler(new DataHandler(source));
				messageBodyPart.setFileName(pieceJointes.get(i));
				multipart.addBodyPart(messageBodyPart);
			}
		}

		msg.setContent(multipart);

		// Send message
		Transport.send(msg);
		LOGGER.info("[MAIL SERVICE] - Mail sent...");
	}

	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it.
	 */
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		public PasswordAuthentication getPasswordAuthentication() {
			String username = smtpAuthUser;
			String password = smtpAuthPassword;
			return new PasswordAuthentication(username, password);
		}
	}

	/**
	 * @param smtpHostName
	 *            the smtpHostName to set
	 */
	public void setSmtpHostName(String smtpHostName) {
		this.smtpHostName = smtpHostName;
	}

	/**
	 * @param smtpAuthUser
	 *            the smtpAuthUser to set
	 */
	public void setSmtpAuthUser(String smtpAuthUser) {
		this.smtpAuthUser = smtpAuthUser;
	}

	/**
	 * @param smtpAuthPassword
	 *            the smtpAuthPassword to set
	 */
	public void setSmtpAuthPassword(String smtpAuthPassword) {
		this.smtpAuthPassword = smtpAuthPassword;
	}

	/**
	 * @param emailFromAddress
	 *            the emailFromAddress to set
	 */
	public void setEmailFromAddress(String emailFromAddress) {
		this.emailFromAddress = emailFromAddress;
	}

	/**
	 * @param mailingDao
	 *            the mailingDao to set
	 */
	public void setMailingDao(MailingDao mailingDao) {
		this.mailingDao = mailingDao;
	}

	/**
	 * @param logDir
	 *            the logDir to set
	 */
	public void setLogDir(String logDir) {
		this.logDir = logDir;
	}

}
